import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class TokenService extends GetxService {
  final _box = GetStorage();
  static const String _tokenKey = 'auth_token';
  static const String _credentialsKey = 'saved_credentials';
  static const String _rememberMeKey = 'remember_me';
  static const String _gbVideoTokenKey = 'gb_video_token'; // 国标视频token的key
  
  // 获取实例的便捷方法
  static TokenService get to => Get.find<TokenService>();
  
  // 初始化
  Future<TokenService> init() async {
    return this;
  }
  
  // 保存token
  void saveToken(String token) {
    _box.write(_tokenKey, token);
  }
  
  // 清除token
  void clearToken() {
    _box.remove(_tokenKey);
  }
  
  // 获取token
  String? getToken() {
    return _box.read<String?>(_tokenKey);
  }
  
  // 检查是否已登录
  bool isLoggedIn() {
    final token = getToken();
    return token != null && token.isNotEmpty;
  }
  
  // 保存记住我状态
  void saveRememberMe(bool remember) {
    _box.write(_rememberMeKey, remember);
  }
  
  // 获取记住我状态
  bool getRememberMe() {
    return _box.read<bool>(_rememberMeKey) ?? false;
  }
  
  // 保存用户凭证
  void saveCredentials(String username, String password) {
    if (getRememberMe()) {
      _box.write(_credentialsKey, {'username': username, 'password': password});
    } else {
      // 如果不记住我，则清除保存的凭证
      clearCredentials();
    }
  }
  
  // 获取保存的凭证
  Map<String, String>? getSavedCredentials() {
    final credentials = _box.read<Map<dynamic, dynamic>>(_credentialsKey);
    if (credentials != null) {
      return {
        'username': credentials['username'],
        'password': credentials['password'],
      };
    }
    return null;
  }
  
  // 清除保存的凭证
  void clearCredentials() {
    _box.remove(_credentialsKey);
  }
  
  // 以下是国标视频平台相关的方法
  
  // 保存国标视频token
  static void saveGBVideoToken(String token) {
    final box = GetStorage();
    box.write(_gbVideoTokenKey, token);
  }
  
  // 获取国标视频token
  static String? getGBVideoToken() {
    final box = GetStorage();
    return box.read<String?>(_gbVideoTokenKey);
  }
  
  // 清除国标视频token
  static void clearGBVideoToken() {
    final box = GetStorage();
    box.remove(_gbVideoTokenKey);
  }
  
  // 检查是否已登录国标视频平台
  static bool isGBVideoLoggedIn() {
    final token = getGBVideoToken();
    return token != null && token.isNotEmpty;
  }
} 